const express = require("express");
let app = express();
app.use(express.json());
const fs = require("fs");
app.post("/addList", (req, res) => {
  try {
    console.log(req.body)
    let todolist = JSON.parse(fs.readFileSync("./todo.json"));
    todolist.push(req.body);
    fs.writeFileSync("./todo.json", JSON.stringify(todolist))
    res.json({
      info: "添加成功",
      status: 1
    })
  } catch (err) {
    res.json({
      info: "添加失败",
      status: 0,
      err
    })
  }

})

app.get("/getlist", (req, res) => {
  let list = JSON.parse(fs.readFileSync("./todo.json"));

  res.json(list);
})

app.put("/ChangeCheck", (req, res) => {
  try {
    let { id } = req.body;
    console.log(id);
    let list = JSON.parse(fs.readFileSync("./todo.json"));
    let index = list.findIndex(item => item.id === id);
    list[index].done = !list[index].done;
    fs.writeFileSync("./todo.json", JSON.stringify(list))
    res.json({
      info: "更新成功",
      status: 1
    })
  } catch (err) {
    console.log(222)
    res.json({
      info: "更新失败",
      status: 0,
      err
    })
  }

})


app.delete("/deltodo", (req, res) => {
  try {
    let { id } = req.query;
    let list = JSON.parse(fs.readFileSync("./todo.json"));
    let arr = list.filter(item => item.id != id);
    fs.writeFileSync("./todo.json", JSON.stringify(arr));
    res.json({
      info: "删除成功",
      status: 1
    })
  } catch (err) {
    res.json({
      info: "删除失败",
      status: 0
    })
  }

})



app.listen(8989);